package org.warehouse.dao.engine;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;

/**
 * Simple unsafe wrapper for 
 * @author test
 *
 */
public class DbExecutor {
	private static DbExecutor instance;

	private final Logger logger = Logger.getLogger(getClass().getSimpleName());
	
	private final String url = "jdbc:mysql://localhost:3306/hr_test";

	private final String username = "root";

	private final String password = "";

	private final Connection connection;

	private DbExecutor() throws DaoException {
		try {
			// Load JDBC driver
			Class.forName("com.mysql.jdbc.Driver");

			// Create connection
			connection = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	public static DbExecutor getInstance() {
		if (instance == null) {
			synchronized (DbExecutor.class) {
	            if (instance == null) {
	            	instance = new DbExecutor();
	            }
            }
		}
		return instance;
	}

	private Connection getConnection() {
		return connection;
	}

	public PreparedStatement getPreparedStatement(String sql) throws DaoException {
//		logger.info("Prepare SQL: " + sql);
		try {
			return getConnection().prepareStatement(sql);
		} catch (SQLException e) {
			throw new DaoException(e);
		}
	}

	public void closePreparedStatement(PreparedStatement ps) throws DaoException {
		try {
			if (ps != null && !ps.isClosed()) {
				ps.close();
			}
		} catch (SQLException e) {
			throw new DaoException(e);
		}
	}
	
	public void closeConnection() throws DaoException {
		try {
			if (getConnection() != null && !getConnection().isClosed()) {
				getConnection().close();
			}
		} catch (SQLException e) {
			throw new DaoException(e);
		}
	}

	public synchronized ResultSet invoke(PreparedStatement ps) throws DaoException {
		try {
			return ps.executeQuery();
		} catch (SQLException e) {
			throw new DaoException(e);
		}
	}

	public synchronized int invokeUpdate(PreparedStatement ps) throws DaoException {
		try {
			return ps.executeUpdate();
		} catch (SQLException e) {
			throw new DaoException(e);
		}
	}
}
